package Controller;


import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import DAO.DAOFactory;
import DAO.EmployeeDAO;
import DAO.RankDAO;
import Model.*;

/**
 * Servlet implementation class RankDetail
 */
@WebServlet("/EmployeeDetail")
public class EmployeeDetail extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public EmployeeDetail() {
        super();
        // TODO Auto-generated constructor stub
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
		throws ServletException, IOException
	{
		Authenticate(request,response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
		throws ServletException, IOException
	{
		Authenticate(request,response);
	}

	protected void Authenticate (HttpServletRequest request, HttpServletResponse response)
		throws ServletException, IOException
	{
		//Authenticate before starting process
		if ( LoginAdmin.CheckObject(request, response) ) {
			doProcess(request,response);
		} else {	//Otherwise Authentication Object not found
			response.sendRedirect(LoginAdmin.LOGIN_CONTROL);
		}
	}
	
	protected void doProcess(HttpServletRequest request, HttpServletResponse response)
		throws ServletException, IOException
	{
		String editEmployeeId = request.getParameter("EditEmployeeId");
		String isSubmit = request.getParameter("IsSubmit");
		String lastEmployeeName = request.getParameter("EmployeeName");
		String employeeNameErrorMsg = "";
		String lastManagerID = request.getParameter("ManagerID");
		String managerIDErrorMsg = "";
		String lastEmail = request.getParameter("Email");
		String emailErrorMsg = "";	
		String lastRankID = request.getParameter("RankID");
		String rankIDErrorMsg = "";	
		String lastIsAdmin = request.getParameter("IsAdmin");
		String isAdminErrorMsg = "";
		String lastDeleteFlag = request.getParameter("DeleteFlag");
		String deleteFlagErrorMsg = "";	
		String resetPassword = "";
		boolean enableArchive = true;
		boolean validatePass = false;
		
		//Functions Specific for Edit Employee
		String actionTargetTail = "";
		String pageTitle = "";
		if (editEmployeeId == null) {		//If this is "Add"
			pageTitle = "Add new Employee";
			resetPassword = "New Employee Password will be set to Employee ID";
		} else {							//Otherwise this is "Edit"
			actionTargetTail = 				//Add Tail
				"?EditEmployeeId=" + editEmployeeId;
			pageTitle = "Editting Employee: " + editEmployeeId;
			//Find if employee is manager
			int empInt = Integer.parseInt(editEmployeeId);
			EmployeeDAO empDAO = 			//get DAO
				DAOFactory.getInstance().getEmployeeDAO();
			ArrayList<EmployeeBean> empList = new ArrayList<EmployeeBean>();
			try {
				empList = empDAO.findNotDeleteEmployeeByManager(empInt);
			} catch(Exception e) {
				e.printStackTrace();
			}
			if ( empList.size() >= 1 ) {	//If this person is a manager
				enableArchive = false;		//Do not allow archiving
			}
			resetPassword = "<a href='EmployeeResetPassword?EmployeeId=" + editEmployeeId + "'>Reset Password to Employee ID</a>";
		}
		
		//Functions for First Load
		if (isSubmit == null)			//If this is first load
		{
			validatePass = false;
			if (editEmployeeId == null)	//If this is "Add Rank"
			{
				//Last Values are empty strings
				lastEmployeeName = "";
				lastManagerID = "";
				lastEmail = "";
				lastRankID = "";
				lastIsAdmin = "";
				lastDeleteFlag = "";
			}
			else						//Otherwise this is "Edit Rank"
			{
				EmployeeDAO empDAO = 	//get DAO
						DAOFactory.getInstance().getEmployeeDAO();
				EmployeeBean employee = new EmployeeBean();
				int empInt = Integer.parseInt(editEmployeeId);
				try{
					employee = empDAO.findEmployeeById(empInt);
				} catch (Exception e) {
					e.printStackTrace();
				}
				lastEmployeeName = employee.getName();
				lastManagerID = employee.getManagerId() + "";
				lastEmail = employee.getEmail();
				lastRankID = employee.getRankID() + "";
				lastIsAdmin = employee.getIsAdmin() + "";
				lastDeleteFlag = employee.getDeleteFlag() + "";
			}
		}
		
		//Functions for Submission
		else	//Otherwise this is submission
		{		//Start Validation
			validatePass = true;
			if (lastEmployeeName.length() == 0) { 
				employeeNameErrorMsg = "Please enter an Employee Name";
				validatePass = false;
			}
			if ( StringToBool(lastDeleteFlag) ) {			//If Delete Flag is true
				//Do not check Manager ID any further as it will be reset later
			} else if (lastManagerID.length() == 0) { 	
				managerIDErrorMsg = "Please enter the Manager ID";
				validatePass = false;
			} else if (! lastManagerID.matches("[0-9]+") ) {
				managerIDErrorMsg = "Manager ID must be a positive number";
				validatePass = false;	
			} else if ( lastManagerID.equals(editEmployeeId) ) {
				// If Manager Id is same as Employee ID: Do Nothing
			} else {
				int managerInt = Integer.parseInt(lastManagerID);
				EmployeeDAO empDAO = 			//get DAO
					DAOFactory.getInstance().getEmployeeDAO();
				EmployeeBean manager = new EmployeeBean();
				manager.setDeleteFlag(true);	//Assume Manager is deleted
				try {
					manager = empDAO.findEmployeeById(managerInt);
				} catch(Exception e) {
					e.printStackTrace();
				}
				if ( manager == null ) {		//If Manager does not exist
					managerIDErrorMsg = "No Employee with this ID exists";
					validatePass = false;					
				} else if (manager.getDeleteFlag() ) {
					managerIDErrorMsg = "This is not a current Employee";
					validatePass = false;
				}
			}
			if (lastEmail.length() == 0) { 
				emailErrorMsg = "Please enter an Email";
				validatePass = false;
			}
		}

		//Finally, decide whether to stay on this page or go back to List
		if (validatePass) {								//If Validation was successful
			EmployeeDAO empDAO = 						//get DAO
					DAOFactory.getInstance().getEmployeeDAO();
			EmployeeBean employee = new EmployeeBean();
			employee.setName(lastEmployeeName);
			employee.setEmail(lastEmail);
			employee.setRankID( Integer.parseInt(lastRankID) );
			employee.setIsAdmin( StringToBool(lastIsAdmin) );
			employee.setDeleteFlag( StringToBool(lastDeleteFlag) );
			if (! employee.getDeleteFlag() )			//If this is NOT delete, parse in Manager ID
			{ employee.setManagerId( Integer.parseInt(lastManagerID) ); }
			if (editEmployeeId == null)					//If this is "Add Employee"
			{
				int tempI = 1;							//Generate Rank ID
				try {
					tempI = empDAO.findNextEmployeeID();
				} catch (Exception e) {
					e.printStackTrace();
				}
				employee.setEmployeeId(tempI);
				if ( employee.getDeleteFlag() )			//If To Delete, Set Manager ID to Employee
				{ employee.setManagerId( employee.getEmployeeId() ); }
				try {
					empDAO.addEmployee(employee);		//Add to DB
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			else										//Otherwise this is "Edit Rank"
			{
				employee.setEmployeeId( Integer.parseInt(editEmployeeId) );
				if ( employee.getDeleteFlag() )			//If To Delete, Set Manager ID to Employee
				{ employee.setManagerId( employee.getEmployeeId() ); }
				try {
					empDAO.updateEmployee(employee);	//Update to DB
				} catch (Exception e) {
					e.printStackTrace();
				}				
			}	
			response.sendRedirect("EmployeeList");		//Redirect here
		} else {			
			request.setAttribute("PageTitle", pageTitle);
			request.setAttribute("ActionTargetTail", actionTargetTail);
			request.setAttribute("LastEmployeeName", lastEmployeeName);
			request.setAttribute("EmployeeNameErrorMsg", employeeNameErrorMsg);
			request.setAttribute("LastManagerID", lastManagerID);
			request.setAttribute("ManagerIDErrorMsg", managerIDErrorMsg);
			request.setAttribute("LastEmail", lastEmail);
			request.setAttribute("EmailErrorMsg", emailErrorMsg);
			request.setAttribute("ResetPassword", resetPassword);
			
			{	//Drop Down List for Rank IDs
				ArrayList<String> optionList = new ArrayList<String>();
				RankDAO rankDAO = DAOFactory.getInstance().getRankDAO();
				ArrayList<RankBean> rankList = new ArrayList<RankBean>();
				try {
					rankList = rankDAO.findAllRank(); 
				} catch (Exception e) {
					e.printStackTrace();
				}
				for (RankBean rank : rankList) {
					StringBuffer option = new StringBuffer();
					option.append("<option value='" + rank.getRank_id() + "' ");
					if ( (rank.getRank_id()+"").equals(lastRankID) )
					{ option.append(" selected "); }
					option.append( " >" + rank.getRank_name() );
					option.append( " (" + rank.getTotal_days() + ")" );
					option.append("</option>");
					optionList.add( option.toString() );
				}
				request.setAttribute("LastRankID", optionList.toArray() );
				request.setAttribute("RankIDErrorMsg", rankIDErrorMsg);
			}
			
			{	//Boolean Checkboxes for IsAdmin
				String checkboxcode = "<input type='checkbox' name='IsAdmin' value='true' ";
				if (StringToBool(lastIsAdmin))
				{ checkboxcode += " checked "; }
				checkboxcode += " />";
				request.setAttribute("LastIsAdmin", checkboxcode);
			}
			request.setAttribute("IsAdminErrorMsg", isAdminErrorMsg);
			
			if (enableArchive) {
				//Boolean Checkboxes for Delete Flag
				String checkboxcode = "<input type='checkbox' name='DeleteFlag' value='true' ";
				if (StringToBool(lastDeleteFlag))
				{ checkboxcode += " checked "; }
				checkboxcode += " />";
				request.setAttribute("LastDeleteFlag", checkboxcode + " On Archive, Manager ID will be reset to this Employee");
			} else {
				request.setAttribute("LastDeleteFlag", "Cannot Archive Manager of Current Employees");
			}
			request.setAttribute("DeleteFlagErrorMsg", deleteFlagErrorMsg);

			RequestDispatcher rd = request.getRequestDispatcher("EmployeeDetail.jsp");
			rd.forward(request, response);												//Dispatch to View
		}
	}

	private static boolean StringToBool(String input) 
	{
		boolean output = false;
		if ( input == null ) {	//If Admin was not submitted
			output = false;
		} else if ( input.equals("") ) {
			output = false;
		} else if ( input.equals("false") ) {
			output = false;			
		} else if ( input.equals("true") ) {
			output = true;
		} else {
			System.out.println("Unrecognized 'input': " + input);
		}
		return output;
	}
}
